#include "usersession.h"
#include <QCryptographicHash>
#include <QTimer>
#include <QSettings>
#include <QDebug>

// 会话超时时间(分钟)
const int SESSION_TIMEOUT = 30;
// 会话超时警告提前时间(秒)
const int SESSION_WARNING_TIME = 300;

UserSession::UserSession(QObject *parent)
    : QObject(parent)
    , m_isLoggedIn(false)
    , m_sessionTimeoutMinutes(30)
    , m_sessionTimer(new QTimer(this))
{
    connect(m_sessionTimer, &QTimer::timeout, this, &UserSession::onSessionTimeout);
    m_sessionTimer->start(60000); // 每分钟检查一次
}

UserSession::~UserSession()
{
    // 析构函数实现
}

bool UserSession::authenticateUser(const QString &username, const QString &password)
{
    // 在实际项目中，这里应该查询数据库验证用户凭证
    // 这里使用简化版的认证逻辑作为示例

    // 检查用户名和密码是否为空
    if (username.isEmpty() || password.isEmpty()) {
        return false;
    }

    // 在实际应用中，密码应该使用安全的哈希算法存储和比较
    // 这里只是简单演示
    if (username == "admin" && password == "admin123") {
        m_userId = "admin";
        m_userName = "Administrator";
    } else if (username == "user" && password == "user123") {
        m_userId = "user";
        m_userName = "Standard User";
    } else {
        return false;
    }

    m_loginTime = QDateTime::currentDateTime();
    m_lastActivity = QDateTime::currentDateTime();
    m_isLoggedIn = true;
    m_currentUser = m_userId;
    m_currentUserInfo.username = username;
    m_currentUserInfo.role = (m_userId == "admin") ? USER_ROLE_ADMIN : USER_ROLE_VIEWER;

    emit loginStatusChanged(true);
    emit currentUserChanged(m_userId);
    return true;
}

void UserSession::logoutUser()
{
    if (m_isLoggedIn) {
        clearSession();
        emit loginStatusChanged(false);
    }
}

bool UserSession::isLoggedIn() const
{
    return m_isLoggedIn;
}

QString UserSession::getCurrentUser() const
{
    return m_currentUser;
}

QString UserSession::getCurrentUserRole() const
{
    return userRoleToString(m_currentUserInfo.role);
}

UserRole UserSession::getCurrentUserRoleEnum() const
{
    return m_currentUserInfo.role;
}

UserInfo UserSession::getCurrentUserInfo() const
{
    return m_currentUserInfo;
}

void UserSession::onSessionTimeout()
{
    if (!m_isLoggedIn) {
        return;
    }

    qint64 inactiveSeconds = m_lastActivity.secsTo(QDateTime::currentDateTime());
    qint64 remainingSeconds = m_sessionTimeoutMinutes * 60 - inactiveSeconds;

    if (remainingSeconds <= 0) {
        qInfo() << "Session timed out for user:" << m_currentUser;
        logoutUser();
        emit sessionTimeout();
    }
}

void UserSession::refreshSession()
{
    if (m_isLoggedIn) {
        m_lastActivity = QDateTime::currentDateTime();
    }
}

void UserSession::clearSession()
{
    m_currentUser.clear();
    m_currentUserInfo = UserInfo();
    m_loginTime = QDateTime();
    m_lastActivity = QDateTime();
    m_isLoggedIn = false;
}

bool UserSession::isSessionValid() const
{
    if (!m_isLoggedIn) {
        return false;
    }
    
    qint64 inactiveSeconds = m_lastActivity.secsTo(QDateTime::currentDateTime());
    return inactiveSeconds < (m_sessionTimeoutMinutes * 60);
}

int UserSession::getSessionTimeoutMinutes() const
{
    return m_sessionTimeoutMinutes;
}

void UserSession::setSessionTimeoutMinutes(int minutes)
{
    m_sessionTimeoutMinutes = minutes;
}

QString UserSession::userRoleToString(UserRole role) const
{
    switch (role) {
        case USER_ROLE_ADMIN: return "Administrator";
        case USER_ROLE_OPERATOR: return "Operator";
        case USER_ROLE_VIEWER: return "Viewer";
        default: return "Unknown";
    }
}

UserRole UserSession::stringToUserRole(const QString& roleStr) const
{
    if (roleStr == "Administrator") return USER_ROLE_ADMIN;
    if (roleStr == "Operator") return USER_ROLE_OPERATOR;
    if (roleStr == "Viewer") return USER_ROLE_VIEWER;
    return USER_ROLE_VIEWER;
}

// 简化实现的其他方法
bool UserSession::createUser(const QString& username, const QString& password, 
                           const QString& fullName, UserRole role)
{
    Q_UNUSED(username)
    Q_UNUSED(password)
    Q_UNUSED(fullName)
    Q_UNUSED(role)
    return false; // 简化实现
}

bool UserSession::deleteUser(const QString& username)
{
    Q_UNUSED(username)
    return false; // 简化实现
}

bool UserSession::changeUserPassword(const QString& username, const QString& newPassword)
{
    Q_UNUSED(username)
    Q_UNUSED(newPassword)
    return false; // 简化实现
}

bool UserSession::updateUserInfo(const QString& username, const UserInfo& userInfo)
{
    Q_UNUSED(username)
    Q_UNUSED(userInfo)
    return false; // 简化实现
}

QList<UserInfo> UserSession::getAllUsers() const
{
    return QList<UserInfo>(); // 简化实现
}

bool UserSession::validatePassword(const QString& password) const
{
    return password.length() >= 6; // 简化实现
}

QString UserSession::getPasswordRequirements() const
{
    return "密码长度至少6位"; // 简化实现
}

bool UserSession::loadUserDatabase()
{
    return true; // 简化实现
}

bool UserSession::saveUserDatabase()
{
    return true; // 简化实现
}

QString UserSession::hashPassword(const QString& password, const QString& salt) const
{
    Q_UNUSED(password)
    Q_UNUSED(salt)
    return QString(); // 简化实现
}

QString UserSession::generateSalt() const
{
    return QString(); // 简化实现
}

bool UserSession::verifyPassword(const QString& password, const QString& hash, const QString& salt) const
{
    Q_UNUSED(password)
    Q_UNUSED(hash)
    Q_UNUSED(salt)
    return false; // 简化实现
}

void UserSession::startSessionTimer()
{
    if (m_sessionTimer) {
        m_sessionTimer->start(60000);
    }
}

void UserSession::stopSessionTimer()
{
    if (m_sessionTimer) {
        m_sessionTimer->stop();
    }
}
